<template>
  <div class="change-list-container">
    <el-table
        :data="changeList"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        style="width: 100%">
      <el-table-column prop="changeKey" label="编号" width="60">
        <template #default="{ row }">
          {{ row.changeKey }}
        </template>
      </el-table-column>
      <el-table-column prop="currentStage" label="任务阶段" />
      <el-table-column label="任务状态">
        <template #default="{ row }">
          <el-tag :type="tagTypes[row.approvalStatus]" size="large">
            {{ approvalStatusObj[row.approvalStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="任务创建时间">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="changeCreateTime" label="变更发起时间">
        <template #default="{ row }">
          {{ formatDate(row.changeCreateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" min-width="60">
        <template #default="scope">
          <el-button link type="primary" @click="handleAudit(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import { staticData } from '@/views/project/mixins/staticDataMixin'
import { formatDate} from '@/utils/formatTime'
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  projectCode: {
    type: String,
    required: true
  }
})
const { approvalStatusObj} = staticData()
const tagTypes = {
  1: '',
  2: 'success',
  3: 'error',
}

const { push } = useRouter() // 路由

// 最终展示的变更记录列表
const changeList = ref([])

// 获取变更记录和对应的流程信息
const getChangeListData = async () => {
  try {
    // 1. 获取所有变更记录
    const changeResponse = await IctApi.getAllChangeListByProjectCode({
      project_code: props.projectCode
    })

    if (Object.keys(changeResponse).length === 0) {
      return
    }
    
    // 2. 提取所有的changeKey
    const changeKeys = Object.keys(changeResponse)
    
    // 3. 获取所有变更流程列表
    const processListResponse = await IctApi.getAllChangeProcessList({
      project_code: props.projectCode,
      change_key_list: changeKeys
    })
    
    // 4. 获取每个流程实例的详细信息
    const allProcessDetails = await Promise.all(
      processListResponse.map(async (process) => {
        const processDetail = await BpmApi.getApprovalProcessList({
          processInstanceId: process.id
        })
        const changeKey = process.business_key.split('+')[1]
        return {
          processId: process.id,
          changeKey: changeKey,
          businessKey: process.business_key,
          currentStage: processDetail[0]?.name || '未知阶段',
          createTime: processDetail[0]?.create_time,
          changeCreateTime: processDetail[processDetail.length - 1].create_time,
          approvalStatus: processDetail[0].status
        }
      })
    )
    // 6. 按changeKey排序
    changeList.value = allProcessDetails.sort((a, b) => b.changeKey - a.changeKey)
    
  } catch (error) {
    console.error('获取变更记录失败:', error)
  }
}

// 组件挂载时获取数据
onBeforeMount(() => {
  getChangeListData()
})

const handleAudit = (row: any) => {
  push({
    name: 'ProjectChangeApproval',
    query: {
      project_code: props.projectCode,
      change_key: row.changeKey,
      process_instance_id: row.processId
    }
  })
}
</script>

<style scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');
.change-list-container {
  padding: 20px;
}
</style>